package com.dongbo.recorder.screenrecord.utils.safe;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Debug;
import android.os.Process;

import com.dongbo.recorder.screenrecord.AppLpds;
import com.dongbo.recorder.screenrecord.BuildConfig;
import com.dongbo.recorder.screenrecord.Constants;
import com.dongbo.recorder.screenrecord.utils.MD5;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Locale;

/**
 * author:lutengxuan
 * date:2022/12/8
 * describe:防止被动态调试的解决方法,可以跳过但是有比没有好
 */
public class DebuggerUtils {
    /**
     * 判断当前应用是否是debug状态
     */
    private static boolean isDebuggable(Context context) {
        try {
            ApplicationInfo info = context.getApplicationInfo();
            return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 检测是否在非Debug编译模式下，进行了调试操作，以防动态调试
     *
     * @param context
     * @return
     */
    public static void checkDebuggableInNotDebugModel(Context context) {
        //非Debug 编译，反调试检测
        if (!BuildConfig.DEBUG) {
            if (isDebuggable(context)) {
                finishApp();
            }
            if (!AntiHijackingUtils.getinstance().onCheckSignature(getSignature())) {
                finishApp();
            }
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            //每隔300ms检测一次
                            Thread.sleep(300);
                            //判断是否有调试器连接，是就退出
                            if (Debug.isDebuggerConnected()) {
                                finishApp();
                            }
                            //判断是否被其他进程跟踪，是就退出
                            if (isUnderTraced()) {
                                finishApp();
                            }
                            checkDebuggable();
                            //循环检查端口 5D8A转化成十进制就是23946
                            if (isLoclePortUsing(23946)) {
                                finishApp();
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }, "SafeGuardThread");
            t.start();
        }
        if (isUnderTraced()) {
//            ToastUtils.show("已被其他恶意进程跟踪");
            finishApp();
        }
        checkDebuggable();
    }

    private static void finishApp() {
        //进程自杀
        int myPid = Process.myPid();
        Process.killProcess(myPid);
        //异常退出虚拟机
        System.exit(1);
    }

    private static void checkDebuggable() {//是有比没有好 通过反射重写xposed设置，直接禁用
        try {
            Field v0_1 = ClassLoader.getSystemClassLoader()
                    .loadClass("de.robv.android.xposed.XposedBridge")
                    .getDeclaredField("disableHooks");
            v0_1.setAccessible(true);
            v0_1.set(null, Boolean.valueOf(true));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 当我们使用Ptrace方式跟踪一个进程时，目标进程会记录自己被谁跟踪，可以查看/proc/pid/status看到这个信息,而没有被调试的时候TracerPid为0
     *
     * @return
     */
    private static boolean isUnderTraced() {
        String processStatusFilePath = String.format(Locale.US, "/proc/%d/status", Process.myPid());
        File procInfoFile = new File(processStatusFilePath);
        try {
            BufferedReader b = new BufferedReader(new FileReader(procInfoFile));
            String readLine;
            while ((readLine = b.readLine()) != null) {
                if (readLine.contains("TracerPid")) {
                    String[] arrays = readLine.split(":");
                    if (arrays.length == 2) {
                        int tracerPid = Integer.parseInt(arrays[1].trim());
                        if (tracerPid != 0) {
                            return true;
                        }
                    }
                }
            }
            b.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private static String getSignature() {
        Context ctx = AppLpds.getInstance().getApplicationContext();
        try {
            PackageInfo packageInfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(),
                    PackageManager.GET_SIGNATURES);
            Signature[] signatures = packageInfo.signatures;
            StringBuilder builder = new StringBuilder();
            for (Signature signature : signatures) {
                builder.append(signature.toCharsString());
            }
            return MD5.getMessageDigest(Constants.SIGN_KEY + ctx.getPackageName()) + builder + "appsign=";
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    /***
     *  true:already in using  false:not using
     * @param port
     */
    public static boolean isLoclePortUsing(int port) {
        boolean flag = true;
        try {
            flag = isPortUsing("127.0.0.1", port);
        } catch (Exception e) {
        }
        return flag;
    }

    /***
     *  true:already in using  false:not using
     * @param host
     * @param port
     * @throws UnknownHostException
     */
    public static boolean isPortUsing(String host, int port) throws UnknownHostException {
        boolean flag = false;
        InetAddress theAddress = InetAddress.getByName(host);
        try {
            Socket socket = new Socket(theAddress, port);
            flag = true;
        } catch (IOException e) {
        }
        return flag;
    }

}
